package com.software.lineragent.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.software.common.CommonUtils;
import com.software.form.bookingform.dao.BookingForm;
import com.software.form.bookingform.dao.BookingFormTransaction;

public class LinerQueryServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		BookingFormTransaction bft = (BookingFormTransaction) CommonUtils.getBean("bookingFormTransaction");
		String email = (String) request.getSession().getAttribute("user");
		List<BookingForm> bookings = bft.getFormByEmail(email,0);
		if(bookings != null){
			if(bookings.size() > 0){
				List list = new ArrayList();
				for(int i = 0; i < bookings.size(); i++)
				{
					JSONArray array = new JSONArray();
					array.put(bookings.get(i).getId());
					array.put(bookings.get(i).getShipper());
					array.put(bookings.get(i).getConsignee());
					list.add(array);
				}
				JSONObject o = new JSONObject();
				try {
					o.put("bookings", list);
					CommonUtils.outputJsonData(o.toString(), response);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		JSONObject o = CommonUtils.readJSONStringFromRequestBody(request, response);
		BookingFormTransaction bft = (BookingFormTransaction) CommonUtils.getBean("bookingFormTransaction");
		try {
			int id = o.getInt("id");
			request.getSession().setAttribute("booking_id", id);
			BookingForm bf = bft.getBookingFormById(id);
			if(bf != null){
				JSONObject json = new JSONObject();
				json.put("shipper", bf.getShipper());
				json.put("consignee", bf.getConsignee());
				json.put("notifyparty", bf.getNp());
				json.put("placeofreceipt", bf.getPor());
				json.put("portofloading", bf.getPol());
				json.put("oceanvessel", bf.getOv());
				json.put("portofdischarge", bf.getPodis());
				json.put("placeofdelivery", bf.getPodel());
				json.put("mark", bf.getMark());
				json.put("pkgs", bf.getNop());
				json.put("type", bf.getType());
				json.put("kgs", bf.getKgs());
				json.put("m3", bf.getM3());
				CommonUtils.outputJsonData(json.toString(), response);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
